import { messages, queryCurrencyPrecision, deepCopy } from 'share/common';
import React from 'react';
import {Badge, Button, Card, Col, Form, message, Modal, Popconfirm, Popover, Row, Table,} from 'antd';
import mileageExpenseService
  from 'containers/mileage-subsidy-expense/mileage-subsidy-expense.service';
import 'styles/mileage-subsidy-expense/mileage-subsidy-expense.scss';
import SlideFrame from 'components/slide-frame';
import NewSubsidy from 'containers/mileage-subsidy-expense/new-subsidy';
import menuRoute from 'routes/menuRoute';
import moment from 'moment';
import noInfo from 'images/no-info.png';
import NewExpense from 'containers/my-account/new-expense';
import Condition from 'components/condition';
import Skeleton from 'components/skeleton';
import ResizeTable from 'components/resize-table';
import WayPointMap from 'containers/mileage-subsidy-expense/components/way-point-map';

const { If, Else } = Condition;

class MileageSubsidyExpense extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      infoLoading: true,
      dateList: [],
      data: [],
      totalSubsidy: 0, //补贴总额
      totalMileage: 0, //累计里程
      referenceMileage: 0, //参考里程
      currency: 'CNY',
      isInvoice: 0, //生成费用标识
      invoiceOID: '',
      columns:[
        {
          title: messages('mileage-subsidy-expense.key1'/*出发信息*/),
          dataIndex: 'start',
          width: '25%',
          render:(record, index) => {
            return <div>
              <div>
                {moment(index.departTime).format('YYYY-MM-DD HH:mm')}
              </div>
              <div>{record.place}</div>
              {this.renderOrigin(index.originStart)}
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key2'/*到达信息*/),
          dataIndex: 'end',
          width:'25%',
          render:(record, index) =>{
            return <div>
              <div>
                {moment(index.arriveTime).format('YYYY-MM-DD HH:mm')}
              </div>
              <div style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {record.place}
              </div>
              {this.renderOrigin(index.originEnd)}
            </div>
          }
        },
        {
          title: messages('mileage-subsidy-expense.key24'/*里程*/) + '(KM)',
          dataIndex: 'mileage',
          width: '15%',
          render: (value, record) => (
            <div>
              <div>{messages('mileage-subsidy-expense.key24')/*里程*/}:{value.toFixed(2)}</div>
              {!!record.travelMileage &&  <div>{messages('mileage-subsidy-expense.key66')/*行驶里程*/}:{(record.travelMileage).toFixed(2)}</div>}
              <div>{messages('mileage-subsidy-expense.key67')/*参考里程*/}:{record.referenceMileage && record.referenceMileage.toFixed(2)}</div>
            </div>
          )
        },
        {
          title: messages('mileage-subsidy-expense.key6'/*事由说明*/),
          dataIndex: 'remark',
          render: value => <Popover content={value}>{value}</Popover>
        },
        {
          title: messages('mileage-subsidy-expense.key51')/*创建方式*/,
          dataIndex: 'createdMode',
          render: value => this.renderMode(value)
        },
        {
          title: messages('mileage-subsidy-expense.key25'/*操作*/),
          dataIndex: '',
          render: (text,record) => (
            <section className="mileage-subsidy-operation">
              <WayPointMap record={record} className="mileage-subsidy-operation__a_long" />
              <a className="mileage-subsidy-operation__a" onClick={e => this.handleUnitEdit(e, record)}>{messages('common.edit')}</a>
              <Popconfirm
                title={messages('common.confirm.delete')}
                onConfirm={e => this.deleteUnitRule(e, record)}>
                <a className="mileage-subsidy-operation__a" onClick={e => { e.stopPropagation(); }}>{messages('common.delete')}</a>
              </Popconfirm>
            </section>
          )
        }
      ],
      frameData: {},
      showSlideFrame: false,
      steps: [],
      priceList: [],
      display: 'none',
      newMileageCost: menuRoute.getRouteItem('new-mileage-cost', 'key'),
      tabDate: null,
      createInvoice: true, //true表示能生成费用 false表示已经生成费用,
      showExpenseFlag: false,
      nowExpense: null,
      expenseSource: '',
      isShow: true,
      dataSources: [],
      selectedRowKeys: [],
      mileageDetail: {},
      page: 0,
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        onChange: this.onChangePaper,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100', '200'],
        onShowSizeChange: this.onChangePagerSize,
      },
      selectedDate: void 0
    }
  }

  componentDidMount() {
    this.handleInitData();
  }

  handleInitData = (isRefreshHeader) => {
    let { isShow, dataSources, infoLoading, mileageDetail, selectedDate, createInvoice, selectedRowKeys, loading, invoiceOID } = this.state;
    isRefreshHeader ? loading = false : loading = true;
    infoLoading = true;
    isShow = true;
    const getDetail = () => {
      mileageExpenseService.getMileageDetails({ orderIds: selectedRowKeys })
        .then(res => {
          if (res && res.data) {
            mileageDetail = res.data;
            if (!isRefreshHeader && res.data['detailList'] && res.data['detailList'][0]) {
              dataSources = res.data['detailList'];
              dataSources.map((item, index) => {
                item.content = [];
                if (index === 0) {
                  item.selected = true;
                }
                Object.keys(item)
                  .forEach(key => {
                    if (key === 'price') {
                      item.content.unshift(
                        {
                          key: 'price',
                          name: messages('mileage-subsidy-expense.key52')/*补贴总额：*/,
                          value: item.currency + ' ' + this.filterMoney(item[key], queryCurrencyPrecision(item.currency), true)
                        }
                      );
                    }
                    if (key === 'mileage') {
                      item.content.push({
                        key: 'mileage',
                        name: messages('mileage-subsidy-expense.key53')/*累积里程：*/,
                        value: item[key] + ' KM',
                        referenceMileage: messages('mileage-subsidy-expense.key54', { arg1: item.referenceMileage })/*（参考里程{arg1} KM）*/
                      });
                    }
                  });
                item.steps = item.steps.filter((step) => (step.amount > 0));
              });

              if (mileageDetail.manyInvoice === '1') {
                selectedDate = res.data['detailList'][0].date;
                createInvoice = res.data['detailList'][0].createInvoice;
                invoiceOID =  res.data['detailList'][0].invoiceOID
              } else {
                selectedDate = void 0;
                createInvoice = true;
              }
            } else {
              if (isRefreshHeader) {
                if (mileageDetail.manyInvoice === '1') {
                  dataSources.some(data => {
                    if (data.date === selectedDate) {
                      data.contentV2 = deepCopy(data.content);
                      data.contentV2.map(item => {
                        if (item.key === 'price') {
                          item.value = data.currency + ' ' + this.filterMoney(mileageDetail.totalPrice, queryCurrencyPrecision(item.currency), true);
                        }
                        if (item.key === 'mileage') {
                          item.value = mileageDetail.totalMileage + ' KM';
                          item.referenceMileage = messages('mileage-subsidy-expense.key54', { arg1: mileageDetail.totalReferenceMileage }); /*（参考里程{arg1} KM）*/
                        }
                      });
                      data.stepsV2 = mileageDetail.totalSteps.filter((step) => (step.amount > 0));
                      return true;
                    }
                  });
                } else {
                  mileageDetail.totalSteps = mileageDetail.totalSteps.filter((step) => (step.amount > 0));
                }
              } else {
                selectedDate = void 0;
                isShow = false;
              }
            }
          }
        })
        .finally(() => {
          infoLoading = false;
          this.setState({
            isShow,
            invoiceOID,
            dataSources,
            infoLoading,
            mileageDetail,
            selectedDate,
            createInvoice
          }, () => {!isRefreshHeader && this.getOrders();});
        });
    };
    this.setState({ infoLoading, loading }, getDetail);
  };

  //获取订单
  getOrders() {
    let { data, loading, pagination, page, selectedDate } = this.state;
    const params = { date: selectedDate, page, size: pagination.pageSize, isInvoice: 0 };
    const _getOrder = () => {
      mileageExpenseService.getOrders(params)
        .then(res => {
          data = res.data['orders'] || [];
          pagination.total = Number(res.data.total) || 0;
          pagination.current = page + 1;
        })
        .finally(() => {
          loading = false;
          this.setState({ loading, data, pagination });
        });
    };
    this.setState({ loading: true }, _getOrder);
  }

  //新建里程补贴
  handleNewSubsidy = () => {
    this.setState({
      frameData: {
        isNew: true,
        record: null
      },
      showSlideFrame: true
    })
  };

  //编辑
  handleUnitEdit = (e, record) => {
    this.setState({
      frameData: {
        isNew: false,
        record: record
      },
      showSlideFrame: true
    })
  };

  handleRowClick = record => {
    this.setState({
      frameData: {
        isNew: false,
        record: record
      },
      showSlideFrame: true
    })
  };

  //删除
  deleteUnitRule = (e, record) => {
    e.preventDefault();
    this.setState({ loading:true });
    mileageExpenseService.deleteOrder(record.id).then(response => {
      if (response.status === 200) {
        this.setState({ loading: false });
        message.success(messages('common.delete.success',{ name: '' }));
        this.handleInitData();
      }
    }).catch(() => {
      this.setState({ loading: false });
      message.error(messages('common.operate.filed'));
    })
  };

  //关闭slide刷新列表
  handleCloseSlide = success => {
    this.setState({ showSlideFrame: false }, () => {
      if (success) {
        this.handleInitData();
      }
    })
  };

  showConfirm = () => {
    const { newMileageCost, invoiceOID, selectedRowKeys } = this.state;
    Modal.confirm({
      title: messages('mileage-subsidy-expense.key26'/*里程补贴费用每月只生成一次*/),
      content: messages('mileage-subsidy-expense.key27'/*请确认本月里程已全部记录*/),
      okText: messages('common.ok'),
      cancelText: messages('common.cancel'),
      onOk: () => {
        this.context.router.push(
          newMileageCost.url.replace(/(\w*):order\/:type\/:invoiceOID/, `$1${[selectedRowKeys.join(','), 'new-cost', invoiceOID || 'undefined'].join('/')}`)
      )
      }
    });
  };

  handleCloseExpense = () => {
    this.setState({ showExpenseFlag: false })
  };

  handleShowInvoice = (e) => {
    e.stopPropagation();
    mileageExpenseService.getFeeDetail(this.state.invoiceOID)
      .then(res => {
        this.setState({
          nowExpense: res.data,
          showExpenseFlag: true
        });
      });
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, this.getOrders);
    }
  };

  onChangePagerSize = (current, size) => {
    let { pagination } = this.state;
    if (size !== pagination.pageSize && pagination.total > pagination.pageSize) {
      pagination.pageSize = size;
      pagination.current = 1;
      this.setState({ pagination }, this.getOrders);
    }
  };

  handleSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys }, () => { this.handleInitData(!!selectedRowKeys[0]);});
  };

  handleProductInvoice = () => {
    const { newMileageCost, invoiceOID, selectedRowKeys, mileageDetail } = this.state;
    if (mileageDetail.manyInvoice === '2') {
      this.context.router.push(
        newMileageCost.url.replace(/(\w*):order\/:type\/:invoiceOID/, `$1${[selectedRowKeys.join(','), 'new-cost', invoiceOID || 'undefined'].join('/')}`)
      );
    } else {
      this.showConfirm();
    }
  };

  handleSelectMonth = (data) => {
    let { dataSources } = this.state;
    let flag = true;
    dataSources.map(item => {
      item.selected && item.date === data.date && (flag = false);
      item.selected = item.date === data.date;
    });
    flag && this.setState({
      dataSources,
      selectedRowKeys: [],
      selectedDate: data.date,
      invoiceOID: data.invoiceOID || '',
      createInvoice: data.createInvoice
    }, this.getOrders);
  };

  renderOrigin = (location) => {
    if (!location) {
      return '';
    }
    return(
    <Popover content={location.place}>
      <div className="mileage-point-row_origin">
        {messages('mileage-subsidy-expense.key59')/*[原定位]*/} {location.place}
      </div>
    </Popover>)
  };

  renderExpanded = (record) => {
    return record['viaPoints'] && record['viaPoints'][0]
      ? (
        <section className="mileage-point">
          {
            record['viaPoints'].map(value =>
              <Row className="mileage-point-row">
                <Col span={4}>
                  {moment(value.arrivalTime).format('YYYY-MM-DD HH:mm:ss')}
                </Col>
                <Col span={10}>
                  {value.place}
                </Col>
                <If value={value.originPoint}>
                  <Col span={10} className="mileage-point-row_origin">
                    {messages('mileage-subsidy-expense.key59')/*[原定位]*/} {value.originPoint && JSON.parse(value.originPoint).place}
                  </Col>
                </If>
              </Row>
            )}
        </section>
      )
      : null;
  };

  renderMode = (value) => {
    if (value === 1001) {
      return messages('mileage-subsidy-expense.key55')/*手工创建*/;
    }
    if (value === 1002) {
      return messages('mileage-subsidy-expense.key56')/*定位创建*/;
    }
    return '-';
  };

  renderActions = (action) => {
    return (
      action
        ? <span  className="mileage--card-action"><Badge status="warning" text={messages('mileage-subsidy-expense.key57')/*当月未生成费用*/}/></span>
        : <span className="mileage--card-action" onClick={this.handleShowInvoice}>{messages('mileage-subsidy-expense.key31')/*查看费用*/}</span>
    );
  };

  renderPopover = (item) => {
    const { selectedRowKeys } = this.state;
    const popoverColumns = [
      {
        title: messages('mileage-subsidy-expense.key15'/*里程数*/),
        dataIndex: 'startUnit',
        render: (value, record) => record.startUnit.toFixed(2) + '~' + (record.endUnit === -1 ? messages('mileage-subsidy-expense.key29'/*以上*/) : record.endUnit.toFixed(2))
      },
      {
        title: messages('mileage-subsidy-expense.key16'/*单价/KM*/),
        dataIndex: 'unitPrice',
      },
      {
        title: messages('mileage-subsidy-expense.key8'/*金额*/),
        dataIndex: 'amount'
      }
    ];
    const content = (
      <Table
        size="small"
        columns={popoverColumns}
        pagination={false}
        dataSource={item.selected && selectedRowKeys[0] ? item.stepsV2 : item.steps || item['totalSteps']}/>
    );
    return (
      <Popover
        title={messages('mileage-subsidy-expense.key58')/*计价明细*/}
        content={content}
        placement="bottomLeft">
        <a className="valuation-detail">{messages('mileage-subsidy-expense.key14')/*查看计价明细*/}</a>
      </Popover>
    );
  };

  renderCards = () => {
    const { dataSources, mileageDetail, selectedRowKeys } = this.state;
    return (
      mileageDetail.manyInvoice === '1'
        ? <section className="mileage--date">
          {
            dataSources.map(item =>
              <Card
                onClick={() => this.handleSelectMonth(item)}
                actions={[this.renderActions(item.createInvoice)]}
                hoverable
                className={`mileage--card ${item.selected && 'mileage--card-selected'}`}>
                <div className="mileage--card-header">
                  <h3>
                    {item.date}
                  </h3>
                  {this.renderPopover(item)}
                </div>
                {(item.selected && selectedRowKeys[0] ? item.contentV2 || [] : item.content).map(content =>
                  <p className="mileage--card-content">
                    {content.name}{content.value}{content.referenceMileage}
                  </p>
                )}
              </Card>)
          }
        </section>
        : <section>
          <Row>
            <Col span={4}>
              <span className="info-title">{messages('mileage-subsidy-expense.key13'/*补贴总额*/)}:</span>
            </Col>
            <Col span={4}>
              <span className="info-title">{messages('mileage-subsidy-expense.key11'/*累计里程*/)}:</span>
            </Col>
          </Row>
          <Row>
            <Col span={4} className="info-num">{mileageDetail.currency}&nbsp;{mileageDetail.totalPrice}</Col>
            <Col span={12} className="info-num">
              <span>{mileageDetail.totalMileage}&nbsp;{'KM'}</span>
              <span className="refrer-mileage">
                {messages('mileage-subsidy-expense.key12'/*参考里程(KM)*/) + ':'}{mileageDetail.referenceMileage}&nbsp;{'KM'}
              </span>
              {this.renderPopover(mileageDetail)}
            </Col>
          </Row>
        </section>
    );
  };

  render() {
    const { loading, data, columns, frameData, showSlideFrame, infoLoading, showExpenseFlag, nowExpense, expenseSource, isShow,
      selectedRowKeys, pagination, createInvoice } = this.state;
    const rowSelection = { selectedRowKeys, onChange: this.handleSelectChange };
    return (
      <section className="mileage-subsidy-expense">
        <Button
          type='primary'
          onClick={this.handleNewSubsidy}>
          {messages('mileage-subsidy-expense.key28'/*新建里程补贴*/)}
        </Button>
        <Condition>
          <If value={isShow}>
            <Skeleton loading={infoLoading}>
              <div className="info">
                {this.renderCards()}
              </div>
              <Button disabled={!selectedRowKeys[0] || !createInvoice} onClick={this.handleProductInvoice} type="primary">
                {messages('mileage-subsidy-expense.key30')/*生成费用*/}
              </Button>
            </Skeleton>
            <Skeleton loading={loading}>
              <div className="table-header">
                <div className="table-header-title">{messages('mileage-subsidy-expense.key44', { arg1: pagination.total }/*里程明细共{arg1}条数据*/)}</div>
              </div>
              <ResizeTable
                size="middle"
                rowKey='id'
                columns={columns}
                bordered
                dataSource={data}
                pagination={pagination}
                rowSelection={rowSelection}
                expandedRowRender={this.renderExpanded}
                rowClassName={record => (record.viaPoints || []).length > 0 ? '' : 'row-expand-display-none'}
                onRow={record => ({ onClick: () => this.handleRowClick(record) })}/>
            </Skeleton>
          </If>

          <Else>
            <figure className='pension-logo-icon'>
              <img src={noInfo} alt="no info"/>
              <figcaption>{messages('mileage-subsidy-expense.key46')/*无里程补贴记录，请新增*/}</figcaption>
            </figure>
          </Else>
        </Condition>
        <SlideFrame
          title={frameData.isNew ? messages('mileage-subsidy-expense.key28'/*新建里程补贴*/) : messages('mileage-subsidy-expense.key32'/*编辑里程补贴*/)}
          show={showSlideFrame}
          content={NewSubsidy}
          params={frameData}
          afterClose={this.handleCloseSlide}
          onClose={() => this.setState({ showSlideFrame: false })}/>
        <SlideFrame
          show={showExpenseFlag}
          title={messages('mileage-subsidy-expense.key34')/*编辑费用*/}
          hasFooter={false}
          params={{
            nowExpense,
            expenseSource,
            slideFrameShowFlag: showExpenseFlag,
            readOnly: true,
            hasInit: false
          }}
          content={NewExpense}
          onClose={() => this.setState({
            showExpenseFlag: false,
            nowExpense: null,
            expenseSource: ''
          })}
          afterClose={this.handleCloseExpense}
          width="800px"/>
      </section>
    )
  }
}

MileageSubsidyExpense.contextTypes = {
    router: React.PropTypes.object
};

const wrappedMileageSubsidyExpense = Form.create()(MileageSubsidyExpense);

export default wrappedMileageSubsidyExpense;
